package com.anyikang.volunteer.sos.volunteer.app.mine;

import android.content.ContentValues;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.anyikang.volunteer.sos.volunteer.R;
import com.anyikang.volunteer.sos.volunteer.app.MyConstant;
import com.anyikang.volunteer.sos.volunteer.app.adapter.GridImageAdapter;
import com.anyikang.volunteer.sos.volunteer.app.bean.MyCurrentOrder;
import com.anyikang.volunteer.sos.volunteer.app.bean.Option;
import com.anyikang.volunteer.sos.volunteer.app.bean.User;
import com.anyikang.volunteer.sos.volunteer.app.bean.WrietReportInitData;
import com.anyikang.volunteer.sos.volunteer.app.bean.WrietReportInitJson;
import com.anyikang.volunteer.sos.volunteer.app.view.FullyGridLayoutManager;
import com.anyikang.volunteer.sos.volunteer.utils.CommonUtil;
import com.anyikang.volunteer.sos.volunteer.utils.MyErrorDeal;
import com.anyikang.volunteer.sos.volunteer.utils.ToastUtils;
import com.anyikang.volunteer.sos.volunteer.utils.okhttputils_callback.StringDialogCallback;
import com.google.gson.Gson;
import com.luck.picture.lib.model.FunctionConfig;
import com.luck.picture.lib.model.LocalMediaLoader;
import com.luck.picture.lib.model.PictureConfig;
import com.lzy.okhttpserver.listener.UploadListener;
import com.lzy.okhttpserver.task.ExecutorWithListener;
import com.lzy.okhttpserver.upload.UploadInfo;
import com.lzy.okhttpserver.upload.UploadManager;
import com.lzy.okhttputils.OkHttpUtils;
import com.yalantis.ucrop.entity.LocalMedia;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

public class WriteReportActivity extends AppCompatActivity implements View.OnClickListener,ExecutorWithListener.OnAllTaskEndListener {

    //picture and video type report
    private RecyclerView recyclerPic;
    private GridImageAdapter adapterPic;
    private RecyclerView recyclerVideo;
    private GridImageAdapter adapterVideo;
    private List<LocalMedia> selectMediaPic = new ArrayList<>();
    private List<LocalMedia> selectMediaVideo = new ArrayList<>();
    private int compressFlag = 1; //1系统自带压缩，2第三方luban压缩压缩
    private boolean theme = false;
    private boolean selectImageType = true; //是否图片类型
    int selectType = LocalMediaLoader.TYPE_VIDEO;

    //text type report
    private TextView tvVolunteerName;
    private TextView tvRescueTime;
    private TextView tvSosTime;
    private TextView tvRescueAddress;
    private TextView tvSosName;
    private EditText edtMemo;
    RadioGroup radioGrpReson;
    RadioGroup radioGrpDealResult;
    Button btUpLoadText;
    Button btUploadPic;
    Button btUploadVideo;

    String TAG = "WriteReportActivity";
    private String mOrderId;
    private ArrayList<Option> radioGrpDealResultOption;
    private ArrayList<Option> radioGrpResonOption;

    private String mSosTime;
    private String mRescueTime;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(TAG, "onCreate");
        setContentView(R.layout.activity_write_report);
        UploadManager.getInstance(getApplicationContext()).getThreadPool().setCorePoolSize(2); //progress
        UploadManager.getInstance(getApplicationContext()).getThreadPool().getExecutor().addOnAllTaskEndListener(this);
        initView();
        initData();
    }


    public void dealGetSuccess(WrietReportInitData data) {
        if (data != null) {

            tvVolunteerName.setText(data.getVolunteerName());

            long sosTime = data.getSosTime();

            //gxw-String correctSosTime = sosTime+"000";
            String correctSosTime = sosTime+"";
            mSosTime = correctSosTime;
            tvSosTime.setText(CommonUtil.getDateTimeYmdHms(Long.parseLong(correctSosTime)));

            long rescueTime = data.getReceiveTime();

           //gxw- String correctRescueTime= rescueTime+"000";
            String correctRescueTime= rescueTime+"";
            mRescueTime = correctRescueTime;
            tvRescueTime.setText(CommonUtil.getDateTimeYmdHms(Long.parseLong(correctRescueTime)));

            tvSosName.setText(data.getSosName());
            tvRescueAddress.setText(data.getSosAddress());
            radioGrpResonOption = data.getSosReason();
            radioGrpDealResultOption = data.getDealResult();

            for (int i = 0; i < radioGrpResonOption.size(); i++) {
                RadioButton radioButton = new RadioButton(WriteReportActivity.this);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                radioButton.setId(100+i);
                radioButton.setText(radioGrpResonOption.get(i).getName());
                radioButton.setLayoutParams(params);
                radioGrpReson.addView(radioButton);
                if(i == 0)
                {
                    radioGrpReson.check(radioButton.getId());
                }
            }


            for (int i = 0; i < radioGrpDealResultOption.size(); i++) {
                RadioButton radioButton = new RadioButton(WriteReportActivity.this);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                radioButton.setText(radioGrpDealResultOption.get(i).getName());
                radioButton.setLayoutParams(params);
                radioButton.setId(200+i);
                radioGrpDealResult.addView(radioButton);
                if(i == 0)
                {
                    radioGrpDealResult.check(radioButton.getId());
                }
            }



        }

        return;
    }

    /**
     * 主要初始化 服务端已经保存的数据，直接贴在文本报告上，无需用户再打字输入
     */
    private void initData() {

        User user = new User(WriteReportActivity.this);
        String token = user.getUserToken();
        Log.i(TAG, "url =" + MyConstant.API_WRITE_REPORT_TEXT_INIT + "token=" + token + ",orderId=" + mOrderId);
        OkHttpUtils
                .get(MyConstant.API_WRITE_REPORT_TEXT_INIT)//
                .tag(MyConstant.API_WRITE_REPORT_TEXT_INIT)//
                .params("tokenId", token)//
                .params("orderId", String.valueOf(mOrderId))
                .execute(new StringDialogCallback(WriteReportActivity.this) {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {

                        int retCode = response.code();
                        if (retCode == 200) {
                            Log.i(TAG, "onSuccess 200 return：" + s);
                            try {
                                WrietReportInitJson wrietReportInitJson = new Gson().fromJson(s, WrietReportInitJson.class);

                                if (wrietReportInitJson.getStatus() == 1)//查询ok
                                {
                                    //
                                    dealGetSuccess(wrietReportInitJson.getData());
                                } else {
                                    String msg = wrietReportInitJson.getMsg();
                                    MyErrorDeal.dealError(msg, WriteReportActivity.this);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            MyErrorDeal.dealHttpError(response, WriteReportActivity.this);
                            Log.i(TAG, "onSuccess " + retCode + "return: " + s);
                        }
                    }

                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {

                        MyErrorDeal.dealHttpError(response, WriteReportActivity.this);

                    }
                });
    }

    public void getLastIntent() {
        Intent i = this.getIntent();
        if (i != null) {
            Bundle b = i.getExtras();
            if (b != null) {
                mOrderId = b.getString("orderId");
            }
        }
        return;
    }

    /**
     * 初始化视图
     */
    private void initView() {
        getLastIntent();
        initTextReport();
        initPicAndVideoReport();
    }

    /**
     * 初始化文字报告 相关的控件
     */
    public void initTextReport() {
        //标题
        TextView tvTitle = (TextView) this.findViewById(R.id.tv_title);
        tvTitle.setText("写报告");
        ImageButton imgBtLeft = (ImageButton) this.findViewById(R.id.imgBtLeft);
        imgBtLeft.setOnClickListener(this);

        tvVolunteerName = (TextView) this.findViewById(R.id.tvVolunteerName);
        tvSosName = (TextView) this.findViewById(R.id.tvSosName);
        tvSosTime = (TextView) this.findViewById(R.id.tvSosTime);
        tvRescueTime = (TextView) this.findViewById(R.id.tvRescueTime);
        tvRescueAddress = (TextView) this.findViewById(R.id.tvRescueAddress);
        radioGrpReson = (RadioGroup) this.findViewById(R.id.radioGrpReson);
        radioGrpDealResult = (RadioGroup) this.findViewById(R.id.radioGrpDealResult);
        edtMemo = (EditText) this.findViewById(R.id.edtMemoTotal);
        btUpLoadText = (Button) this.findViewById(R.id.btUpLoadText);
        btUpLoadText.setOnClickListener(this);

 /*       ArrayList<String> radioGrpResonOption = new ArrayList<String>();
        radioGrpResonOption.add("1a");
        radioGrpResonOption.add("2a");
        radioGrpResonOption.add("3a");
        ArrayList<String> radioGrpDealResultOption = new ArrayList<String>();
        radioGrpDealResultOption.add("1b");
        radioGrpDealResultOption.add("2b");
        radioGrpDealResultOption.add("3b");

        for (int i = 0; i < radioGrpResonOption.size(); i++) {
            RadioButton radioButton = new RadioButton(WriteReportActivity.this);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            radioButton.setText(radioGrpResonOption.get(i).toString());
            radioButton.setLayoutParams(params);
            radioButton.setId(i + 100);
            radioGrpReson.addView(radioButton);
        }
        radioGrpReson.check(100 + 0);

        for (int j = 0; j < radioGrpDealResultOption.size(); j++) {
            RadioButton radioButton = new RadioButton(WriteReportActivity.this);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            radioButton.setText(radioGrpDealResultOption.get(j).toString());
            radioButton.setLayoutParams(params);
            radioButton.setId(j + 200);
            radioGrpDealResult.addView(radioButton);
        }
        radioGrpDealResult.check(200 + 0);

        radioGrpReson.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, @IdRes int k) {
                ToastUtils.showToast(WriteReportActivity.this, "当前选中了求救原因的第" + (k - 100) + "个选项");
            }
        });

        radioGrpDealResult.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, @IdRes int h) {

                ToastUtils.showToast(WriteReportActivity.this, "当前选中了处理结果第" + (h - 200) + "个选项");

            }
        });*/
    }

    /**
     * 初始化选择图片、视频控件
     */
    public void initPicAndVideoReport() {
        recyclerPic = (RecyclerView) this.findViewById(R.id.recyclerPic);
        FullyGridLayoutManager manager = new FullyGridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false);
        recyclerPic.setLayoutManager(manager);
        AddPicClickListerner addpicListener = new AddPicClickListerner();
        adapterPic = new GridImageAdapter(this, addpicListener, recyclerPic.getWidth());
        adapterPic.setSelectMax(3);
        recyclerPic.setAdapter(adapterPic);

        //视频选择
        recyclerVideo = (RecyclerView) this.findViewById(R.id.recyclerVideo);
        FullyGridLayoutManager managerVideo = new FullyGridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false);
        recyclerVideo.setLayoutManager(managerVideo);
        AddVideoClickListerner addVideoListener = new AddVideoClickListerner();
        adapterVideo = new GridImageAdapter(this, addVideoListener, recyclerVideo.getWidth());
        adapterVideo.setSelectMax(3);
        recyclerVideo.setAdapter(adapterVideo);

        //上传图片
         btUploadPic = (Button) this.findViewById(R.id.btUploadPic);
        btUploadPic.setOnClickListener(this);

        //上传视频
         btUploadVideo = (Button) this.findViewById(R.id.btUploadVideo);
        btUploadVideo.setOnClickListener(this);
    }

    public static final String SERVER = "http://server.jeasonlzy.com/OkHttpUtils/";
    //public static final String SERVER = "http://192.168.1.40:8080/ReceiveFile/servlet/ReceiveFileServlet";
    //public static final String URL_FORM_UPLOAD = SERVER+"upload";
    String URL_FORM_UPLOAD = "http://192.168.1.104:8080/ReceiveFile/servlet/ReceiveFileServlet"; //换成自己的测试url地址gxw+


    /**
     * 上传文本报告
     */
    public void uploadTextReport()
    {

        String volunteerName = tvVolunteerName.getText().toString();
        String rescueTime = tvRescueTime.getText().toString();
        String rescueAddress = tvRescueAddress.getText().toString();
        String sosName = tvSosName.getText().toString();
        int reasonSelectIndex =  radioGrpReson.getCheckedRadioButtonId() - 100;
        long reasonSelectCode  = radioGrpResonOption.get(reasonSelectIndex).getCode();

        int dealResultSelectIndex =  radioGrpDealResult.getCheckedRadioButtonId() - 200;
        long dealResultSelectCode  = radioGrpDealResultOption.get(dealResultSelectIndex).getCode();

        String memo = edtMemo.getText().toString();

        JSONObject jsonObjWriteReport = new JSONObject();
        String textReport = null;
        try
        {
            jsonObjWriteReport.put("orderId",mOrderId);
            jsonObjWriteReport.put("sosTime",Long.parseLong(mSosTime));
            jsonObjWriteReport.put("receiveTime",Long.parseLong(mRescueTime));
            jsonObjWriteReport.put("sosName",sosName);
            jsonObjWriteReport.put("volunteerName",volunteerName);
            jsonObjWriteReport.put("sosAddress",rescueAddress);
            jsonObjWriteReport.put("sosReason",reasonSelectCode);
            jsonObjWriteReport.put("dealResult",dealResultSelectCode);
            jsonObjWriteReport.put("memo",memo);
            textReport = jsonObjWriteReport.toString();

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        User user = new User(WriteReportActivity.this);
        String token = user.getUserToken();

        Log.i(TAG, "url =" + MyConstant.API_WRITE_REPORT_TEXT + "token=" + token + ",orderId=" + mOrderId+",textReport="+textReport);
        OkHttpUtils
                .post(MyConstant.API_WRITE_REPORT_TEXT)//
                .tag(MyConstant.API_WRITE_REPORT_TEXT)//
                .params("tokenId", token)//
                .params("orderId", mOrderId)//
                .params("textReport", textReport)
                .execute(new StringDialogCallback(WriteReportActivity.this) {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {

                        int retCode = response.code();
                        if (retCode == 200) {
                            Log.i(TAG, "onSuccess 200 return：" + s);
                            try {

                                JSONObject uploadTextResult = new JSONObject(s);
                                if(uploadTextResult.getInt("status") == 1)
                                {
                                    ToastUtils.showToast(WriteReportActivity.this,"提交成功");
                                    int color_gray = WriteReportActivity.this.getResources().getColor(R.color.color_unsel_gray);
                                    btUpLoadText.setBackgroundColor(color_gray);
                                    btUpLoadText.setEnabled(false);

                                    //更新本地缓存任务单状态为4
                                    MyCurrentOrder currentOrder = new MyCurrentOrder(WriteReportActivity.this);
                                    Log.i(TAG,"before modify id="+currentOrder.getItemId()+",state="+currentOrder.getState()+",sospersonId="+currentOrder.getSosPersonId()+",imei="+currentOrder.getDeviceIMEI());

                                    if(mOrderId.equals(currentOrder.getItemId()))
                                    {
                                        ContentValues values = new ContentValues();
                                        values.put("state",4);
                                        currentOrder.saveCurOrderInfo(WriteReportActivity.this,values);
                                    }

                                    MyCurrentOrder currentOrder2 = new MyCurrentOrder(WriteReportActivity.this);
                                    Log.i(TAG,"after modify id="+currentOrder2.getItemId()+",state="+currentOrder2.getState()+",sospersonId="+currentOrder2.getSosPersonId()+",imei="+currentOrder2.getDeviceIMEI());

                                }
                                else {
                                    String msg = uploadTextResult.getString("msg");
                                    MyErrorDeal.dealError(msg, WriteReportActivity.this);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            MyErrorDeal.dealHttpError(response, WriteReportActivity.this);
                            Log.i(TAG, "onSuccess " + retCode + "return: " + s);
                        }
                    }

                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {

                        MyErrorDeal.dealHttpError(response, WriteReportActivity.this);

                    }
                });
    }


    @Override
    public void onClick(View view) {
        switch (view.getId())
        {

            case R.id.btUpLoadText:

                uploadTextReport();
                break;
            case R.id.btUploadPic:  //上传图片
                ToastUtils.showToast(WriteReportActivity.this,"上传图片");

                if (selectMediaPic != null) {

                    User user = new User(WriteReportActivity.this);
                    String tokenId = user.getUserToken();

                    for (int i = 0; i < selectMediaPic.size(); i++) {
                         MyUploadListener listener = new MyUploadListener();
                        View childView = recyclerPic.getChildAt(i);
                        listener.setUserTag(recyclerPic.getChildViewHolder(childView));
                        HashMap<String ,String> paramMap = new HashMap<String,String>();
                        paramMap.put("tokenId",tokenId);
                        paramMap.put("orderId",mOrderId);
                        Log.i(TAG,"tokenId="+tokenId+",orderId="+mOrderId);
                      //gxw-  UploadManager.getInstance(WriteReportActivity.this).addTask(MyConstant.API_SPOT_IMAGE, new File(selectMediaPic.get(i).getPath()), "imageFile"+(i+1),paramMap, listener);
                        UploadManager.getInstance(WriteReportActivity.this).addTask(MyConstant.API_SPOT_IMAGE, new File(selectMediaPic.get(i).getPath()), "file",paramMap, listener);

                        if(i == 0)
                        {
                          //gxw-可能要恢复  btUploadPic.setEnabled(false);
                        }
                    }
                }
                break;
            case R.id.btUploadVideo:  //上传视频
                ToastUtils.showToast(WriteReportActivity.this,"上传视频");
                if (selectMediaVideo != null) {

                    User user = new User(WriteReportActivity.this);
                    String tokenId = user.getUserToken();
                    for (int i = 0; i < selectMediaVideo.size(); i++) {
                        MyUploadListener listener = new  MyUploadListener();
                        View childView = recyclerVideo.getChildAt(i);
                        listener.setUserTag(recyclerVideo.getChildViewHolder(childView));
                        HashMap<String ,String> paramMap = new HashMap<String,String>();
                        paramMap.put("tokenId",tokenId);
                        paramMap.put("orderId",mOrderId);
                      //gxw-  UploadManager.getInstance(WriteReportActivity.this).addTask(MyConstant.API_SPOT_VIDEO, new File(selectMediaVideo.get(i).getPath()), "imageFile"+(i+1),paramMap, listener);
                        UploadManager.getInstance(WriteReportActivity.this).addTask(MyConstant.API_SPOT_VIDEO, new File(selectMediaVideo.get(i).getPath()), "file",paramMap, listener);
                        if(i == 0)
                        {
                          //gxw-可能要恢复  btUploadVideo.setEnabled(false);
                        }
                    }
                }
                break;
            case R.id.imgBtLeft:   //返回
                WriteReportActivity.this.finish();
        }
    }



    @Override
    public void onAllTaskEnd() {
        Log.i(TAG,"onAllTaskEnd");
        for (UploadInfo uploadInfo : UploadManager.getInstance(WriteReportActivity.this).getAllTask()) {
            if (uploadInfo.getState() != UploadManager.FINISH) {
                //GXW-Toast.makeText(getContext(), "所有上传线程结束，部分上传未完成", Toast.LENGTH_SHORT).show();
                Log.i(TAG,"所有上传线程结束，部分上传未完成");
                btUploadPic.setEnabled(true);
                btUploadVideo.setEnabled(true);

                return;
            }
        }
        //Toast.makeText(getContext(), "所有上传任务完成", Toast.LENGTH_SHORT).show();
        Log.i(TAG,"所有上传任务完成");
        btUploadPic.setEnabled(true);
        btUploadVideo.setEnabled(true);
    }

    private class MyUploadListener extends UploadListener<UploadInfo> {

        private GridImageAdapter.ViewHolder holder;

        @Override
        public void onProgress(UploadInfo uploadInfo) {
            Log.i(TAG,"onProgress"+uploadInfo.getProgress());
            //gxw-Log.e("MyUploadListener", "onProgress:" + uploadInfo.getFileName() + " " + uploadInfo.getTotalLength() + " " + uploadInfo.getUploadLength() + " " + uploadInfo.getProgress());
            GridImageAdapter.ViewHolder view = (GridImageAdapter.ViewHolder) getUserTag();
            holder = view;
            holder.refresh(uploadInfo);
        }

        @Override
        public void onFinish(UploadInfo t) {
            Log.i(TAG,"onFinish");
            Log.e("MyUploadListener", "finish:" + t);
            holder.finish(t);
        }

        @Override
        public void onError(UploadInfo uploadInfo, String errorMsg, Exception e) {
            Log.i(TAG,"onError");
            Log.e("MyUploadListener", "onError:" + errorMsg);
            if(e != null)
            {
                e.printStackTrace();
            }
            //GXW-
        }

        @Override
        public UploadInfo parseNetworkResponse(Response response) throws Exception {

            String ret = response.toString(); //gxw+
            Log.e("MyUploadListener", "parseNetworkResponse:" + ret);
            return null;
        }


    }

    @Override
    protected void onDestroy() {
        Log.i(TAG,"onDestroy");
        UploadManager.getInstance(getApplicationContext()).getThreadPool().getExecutor().removeOnAllTaskEndListener(this);
        super.onDestroy();
    }

    /**
     * 选择图片
     */

    public  class AddPicClickListerner implements GridImageAdapter.onAddPicClickListener{

        @Override
        public void onAddPicClick(int type, int position) {
            switch (type) {
                case 0:
                    // 进入相册

			/*gxw-s	裁剪宽，高暂时不需要
				    String ws = et_w.getText().toString().trim();
					String hs = et_h.getText().toString().trim();
					if (!isNull(ws) && !isNull(hs)) {
						cropW = Integer.parseInt(ws);
						cropH = Integer.parseInt(hs);
					}


					LuBan压缩宽高，暂时不需要

					if (!isNull(et_compress_width.getText().toString()) && !isNull(et_compress_height.getText().toString())) {
						compressW = Integer.parseInt(et_compress_width.getText().toString());
						compressH = Integer.parseInt(et_compress_height.getText().toString());
					}
             gxw-e*/
                    int selector = R.drawable.select_cb;

                    int selectMode = 1;//多选
                    boolean isShow = true; //显示拍照选项，不但可以选择现有图片，还可以拍照
                    boolean enablePreview = true;  //是否启用预览
                    boolean enableCrop = false;  //是否启用裁剪
                    boolean isPreviewVideo = true;  //是否启用预览视频
                    boolean isCheckNumMode = false;  //启用，多选时，图片右上角显示数字

                    FunctionConfig config = new FunctionConfig();
                    config.setType(LocalMediaLoader.TYPE_IMAGE);  //是选择图片还是视频
                    config.setCopyMode(1); //裁剪模式1:1
                    config.setCompress(false); //默认不压缩图片
                    config.setEnablePixelCompress(true);
                    config.setEnableQualityCompress(true);
                    config.setMaxSelectNum(3);  //最多可以选择的图片数量
                    config.setMaxSelectVideo(2);
                    config.setSelectMode(selectMode);
                    config.setShowCamera(isShow);
                    config.setEnablePreview(enablePreview);
                    config.setEnableCrop(enableCrop);
                    config.setPreviewVideo(isPreviewVideo);
                    config.setRecordVideoDefinition(FunctionConfig.HIGH);// 视频清晰度
                    config.setRecordVideoSecond(60);// 视频秒数

					/*gxw-s 裁剪宽高
					config.setCropW(cropW);
					config.setCropH(cropH);
					gxw-e*/
                    config.setCheckNumMode(isCheckNumMode);
                    config.setCompressQuality(100);
                    config.setImageSpanCount(4);
                    config.setSelectMedia(selectMediaPic);
                    config.setCompressFlag(compressFlag);

					/*gxw-s 压缩宽高
					  config.setCompressW(compressW);
					  config.setCompressH(compressH);

					if (theme) {  蓝色主题
						config.setThemeStyle(ContextCompat.getColor(MainActivity.this, R.color.blue));
						// 可以自定义底部 预览 完成 文字的颜色和背景色
						if (!isCheckNumMode) {
							// QQ 风格模式下 这里自己搭配颜色，使用蓝色可能会不好看
							config.setPreviewColor(ContextCompat.getColor(MainActivity.this, R.color.white));
							config.setCompleteColor(ContextCompat.getColor(MainActivity.this, R.color.white));
							config.setPreviewBottomBgColor(ContextCompat.getColor(MainActivity.this, R.color.blue));
							config.setBottomBgColor(ContextCompat.getColor(MainActivity.this, R.color.blue));
						}
					}gxw-e*/
					/*gxw-s 视频类型不需要 if (selectImageType) {
						config.setCheckedBoxDrawable(selector);
					}gxw-e*/
                    config.setCheckedBoxDrawable(selector);
                    // 先初始化参数配置，在启动相册
                    PictureConfig.init(config);
                    PictureConfig.getPictureConfig().openPhoto(WriteReportActivity.this, resultCallback);
                    // 只拍照
                    //PictureConfig.getPictureConfig().startOpenCamera(mContext, resultCallback);
                    break;
                case 1:
                    // 删除图片或视频
                    selectMediaPic.remove(position);
                    adapterPic.notifyItemRemoved(position);
                    break;
            }
        }
    };


    /**
     * 选择视频
     */

    public  class AddVideoClickListerner implements GridImageAdapter.onAddPicClickListener{

        public void onAddPicClick(int type, int position) {
            switch (type) {
                case 0:

			/*gxw-s	裁剪宽，高

				    String ws = et_w.getText().toString().trim();
					String hs = et_h.getText().toString().trim();

					if (!isNull(ws) && !isNull(hs)) {
						cropW = Integer.parseInt(ws);
						cropH = Integer.parseInt(hs);
					}

             gxw-e*/

			  /* LuBan压缩宽高

					if (!isNull(et_compress_width.getText().toString()) && !isNull(et_compress_height.getText().toString())) {
						compressW = Integer.parseInt(et_compress_width.getText().toString());
						compressH = Integer.parseInt(et_compress_height.getText().toString());
					}
				*/

                    int selector = R.drawable.select_cb;
                    int selectMode = 1;//多选
                    boolean isShow = true; //显示拍照选项，不但可以选择现有图片，还可以拍照
                    boolean enablePreview = true;  //是否启用预览
                    boolean enableCrop = false;  //是否启用裁剪
                    boolean isPreviewVideo = true;  //是否启用预览视频
                    boolean isCheckNumMode = false;  //启用，多选时，图片右上角显示数字

                    FunctionConfig config = new FunctionConfig();
                    config.setType(LocalMediaLoader.TYPE_VIDEO);  //是选择图片还是视频
                    config.setCopyMode(1); //裁剪模式1:1
                    config.setCompress(false); //默认不压缩图片
                    config.setEnablePixelCompress(true);
                    config.setEnableQualityCompress(true);
                    config.setMaxSelectNum(3);  //最多可以选择的图片数量
                    config.setMaxSelectVideo(2);
                    config.setSelectMode(selectMode);
                    config.setShowCamera(isShow);
                    config.setEnablePreview(enablePreview);
                    config.setEnableCrop(enableCrop);
                    config.setPreviewVideo(isPreviewVideo);
                    config.setRecordVideoDefinition(FunctionConfig.HIGH);// 视频清晰度
                    config.setRecordVideoSecond(60);// 视频秒数

					/*gxw-s 裁剪宽高
					config.setCropW(cropW);
					config.setCropH(cropH);
					gxw-e*/
                    config.setCheckNumMode(isCheckNumMode);
                    config.setCompressQuality(100);
                    config.setImageSpanCount(4);
                    config.setSelectMedia(selectMediaVideo);
                    config.setCompressFlag(compressFlag);

					/*gxw-s 压缩宽高
					  config.setCompressW(compressW);
					  config.setCompressH(compressH);

					if (theme) {  蓝色主题
						config.setThemeStyle(ContextCompat.getColor(MainActivity.this, R.color.blue));
						// 可以自定义底部 预览 完成 文字的颜色和背景色
						if (!isCheckNumMode) {
							// QQ 风格模式下 这里自己搭配颜色，使用蓝色可能会不好看
							config.setPreviewColor(ContextCompat.getColor(MainActivity.this, R.color.white));
							config.setCompleteColor(ContextCompat.getColor(MainActivity.this, R.color.white));
							config.setPreviewBottomBgColor(ContextCompat.getColor(MainActivity.this, R.color.blue));
							config.setBottomBgColor(ContextCompat.getColor(MainActivity.this, R.color.blue));
						}
					}gxw-e*/

                    config.setCheckedBoxDrawable(selector);


                    // 先初始化参数配置，在启动相册
                    PictureConfig.init(config);
                    PictureConfig.getPictureConfig().openPhoto(WriteReportActivity.this, resultCallbackVideo);

                    break;
                case 1:
                    // 删除视频
                    selectMediaVideo.remove(position);
                    adapterVideo.notifyItemRemoved(position);
                    break;
            }
        }
    };


    /**
     * 图片回调方法
     */
    private PictureConfig.OnSelectResultCallback resultCallback = new PictureConfig.OnSelectResultCallback() {
        @Override
        public void onSelectSuccess(List<LocalMedia> resultList) {
            selectMediaPic = resultList;
            Log.i("callBack_result", selectMediaPic.size() + "");
            if (selectMediaPic != null) {

                adapterPic.setList(selectMediaPic);
                recyclerPic.setAdapter(adapterPic);
               //gxw-adapterPic.notifyDataSetChanged();
            }
        }
    };


    /**
     * 视频回调方法
     */
    private PictureConfig.OnSelectResultCallback resultCallbackVideo = new PictureConfig.OnSelectResultCallback() {
        @Override
        public void onSelectSuccess(List<LocalMedia> resultList) {
            selectMediaVideo = resultList;
            Log.i("callBack_result", selectMediaVideo.size() + "");
            if (selectMediaVideo != null) {
                adapterVideo.setList(selectMediaVideo);
                recyclerVideo.setAdapter(adapterVideo);
               //gxw-adapterVideo.notifyDataSetChanged();
            }
        }
    };
}
